//
//  LBMStatusListViewModel.swift
//  微博
//
//  Created by 刘保满 on 16/5/24.
//  Copyright © 2016年 itheima. All rights reserved.
// tableView的视图模型

import UIKit

class LBMStatusListViewModel: NSObject {
    
    //定义模型数组
    lazy var statusViewModelArray: [LBMStatusViewModel] = [LBMStatusViewModel]()
    
    func loadHomePage(isPulling: Bool, finished: (isSuccess: Bool, count: Int) -> ()) {
        
        var since_id: Int64 = 0
        var max_id: Int64 = 0
        
        //啷个要互斥
        if isPulling {
            
            max_id = statusViewModelArray.last?.status?.id ?? 0
            
        } else {
            
            since_id = statusViewModelArray.first?.status?.id ?? 0
            
        }
        
        //加载网络数据
        
        LBMNetworkTools.sharedTools.loadHomePageData(since_id, max_id: max_id) { (responsseObject, error) in
            
            if error != nil {
                
                //失败
                finished(isSuccess: false, count: 0)
                return
            }
            
            //返回的数据最外层是字典
            guard let dict = responsseObject as? [String: AnyObject] else {
                finished(isSuccess: false, count: 0)
                return
            }
            //根据字典的key "statuses" 取出 数组,这个数组里又是字典
            guard let array = dict["statuses"] as? [[String: AnyObject]] else {
                finished(isSuccess: false, count: 0)
                return
            }
            
            //下面要字典转模型
            var tempArray = [LBMStatusViewModel]()
            for item in array {
                //字典转模型
                let s = LBMStatus(dict: item)
                let viemodel = LBMStatusViewModel(status: s)
                //添加到数组
                tempArray.append(viemodel)
            }
            
            //赋值
            if isPulling {
                //加载更多数据
                self.statusViewModelArray = self.statusViewModelArray + tempArray
                
                
            } else {
                //刷新数据
                self.statusViewModelArray = tempArray  + self.statusViewModelArray
                
                
            }
            
            
            finished(isSuccess: true, count: tempArray.count)
            
        }
        
    }
}
